import { type Options } from './type';
import Copy from './copy';
import { watch, onMounted } from 'vue';
import { v4 } from 'uuid';

export default class extends Copy {
  constructor(options: Options) {
    super(options);
    onMounted(() => {
      watch(() => this.props.keepLastRowEmpty, () => {
        if (this.props.keepLastRowEmpty) this.autokeepLastRowEmpty();
      }, {
        immediate: true
      }) 
    });
    // 内置唯一key
    watch(
      () => this.dataSource.value.length,
      () => {
        if (this.props.readonly === true || this.props.disabled === true) return;
        
        for (const row of this.dataSource.value) {
          if (row[this.props.rowKey]) continue;
          else {
            row[this.props.rowKey] = this.createId();
          }
        }
      },
      { immediate: true },
    );
  }

  setDefaultRowData(rowindex: number) {
    if (event.button === 2) return;
    
    if (!this.dataSource?.value[rowindex]) return;
    this.dataSource.value[rowindex] = Object.assign(
      this.props.defaultRowData?.() ?? {},
      this.dataSource.value[rowindex] ?? {},
    );
  }

  /**
   * 插入行
   * @param rowindex 插入目标行下标
   * @param position 往前插入 还是 往后插入
   * @param length 插入行数，默认1行
   * @param addHistoryRecord 是否需要增加操作记录， 默认需要
   */
  insertRows(
    rowindex: number,
    position: 'before' | 'after',
    length: number = 1,
    addHistoryRecord: boolean = true
  ) {
    if(addHistoryRecord && this.props.openUndo && this.emptyHistoryRecord()) this.addHistoryRecord();
    
    length = Math.floor(length)

    if (rowindex === this.dataSource?.value?.length - 1){
      this.setDefaultRowData(rowindex);
    }
    
    const index = position === 'before' ? rowindex : rowindex + 1;
    const newdata = new Array(length).fill(undefined).map(() => ({
      ...this.props.defaultRowData?.(),
      [this.props.rowKey]: this.createId(),
    }));
    this.dataSource.value.splice(index, 0, ...newdata);
    this.emits('afterInsertEmptyRow', index, newdata);

    if (position === 'before') {
      this.selectedState.startY += length;
      this.selectedState.endY += length;
    }

    if(addHistoryRecord && this.props.openUndo) this.addHistoryRecord();
  }

  insertCopyRows(
    rowindex: number,
    position: 'before' | 'after',
    length: number = 1,
    copyData: { [key: string]: any }[] = [{}],
  ) {
    if(this.props.openUndo && this.emptyHistoryRecord()) this.addHistoryRecord();

    length = Math.floor(length)
    
    const index = position === 'before' ? rowindex : rowindex + 1;
    let copyIndex = 0;
    const newdata = new Array(length).fill(undefined).map(() => {
      if (copyIndex >= copyData.length) copyIndex = 0;

      const row = JSON.parse(
        JSON.stringify({
          ...copyData[copyIndex],
          [this.props.rowKey]: this.createId(),
        }),
      );

      return row;
    });
    this.dataSource.value.splice(index, 0, ...newdata);

    if(this.props.openUndo) this.addHistoryRecord();
  }

  autokeepLastRowEmpty() {
    watch(
      () => Object.keys(this.dataSource?.value.at(-1) ?? {}).length,
      (value) => {

        if (this.props.readonly === true || this.props.disabled === true) return;

        // 因为内置了id, 所有至少是一个参数
        if (value > 1) {
          const newdata = {
            [this.props.rowKey]: this.createId(),
          };
          this.dataSource?.value.push(newdata);
          this.emits(
            'afterInsertEmptyRow',
            this.dataSource?.value.length - 2,
            newdata,
          );

          if(
            this.selectedState.startX !== undefined &&
            this.selectedState.endY !== undefined && 
            this.selectedState.startX === this.selectedState.endX && 
            this.selectedState.startY === this.selectedState.endY
          ){
            // Promise.resolve().then(() => {
            //   this.table.value?.querySelector('tbody>tr:last-child')?.scrollIntoView({ block: "end", behavior: "smooth" })
            // })
            setTimeout(() => {
              this.table.value?.querySelector('tbody>tr:last-child')?.scrollIntoView({ block: "nearest", behavior: "smooth" })
              this.currentView = true
              this.getCellElement({rowindex: this.selectedState.startY, colindex: this.selectedState.startX})?.click?.()
            }, 0)
          }
        }
        // 表格数据删除完，需要自动补1行
        if (value === 0) {
          this.insertRows(0, 'after', 1, false);
        }
      },
      { immediate: true },
    );
  }

  createId() {
    return v4();
  }
}
